package cn.cdeden.knowledge.controller.corporate;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.oss.enumd.OssModuleType;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.PersonalFilesTree;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.vo.PersonalFilesTreeVo;
import cn.cdeden.knowledge.service.EnterpriseFilesTreeService;
import cn.cdeden.knowledge.service.FileService;
import cn.cdeden.knowledge.service.PersonalFilesTreeService;
import cn.cdeden.resource.api.RemoteOssEsService;
import cn.cdeden.resource.api.domain.RemoteEsFilesTree;
import cn.cdeden.system.api.RemoteConfigService;
import cn.cdeden.system.api.RemoteLargeModelService;
import cn.cdeden.system.api.model.LoginUser;
import io.undertow.util.BadRequestException;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * 个人文档
 */
@Controller
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/personalTreeFile")
public class PersonalTreeController {

    private final PersonalFilesTreeService personalFilesTreeService;

    private final FileService fileService;

    private final EnterpriseFilesTreeService enterpriseFilesTreeService;

    @DubboReference(check = false)
    private final RemoteOssEsService remoteOssEsService;

    @DubboReference(check = false)
    private final RemoteLargeModelService remoteLargeModelService;

    @DubboReference(check = false)
    private final RemoteConfigService remoteConfigService;



//    @ApiOperation("个人文档:查询个人树")

    /**
     * 个人文档:查询个人树
     * @param query
     * @return
     * @throws BadRequestException
     */
    @GetMapping(value = "/selectTree")
    public R<PersonalFilesTreeVo> selectTree(PersonalFilesTreeParam query) throws BadRequestException {
        PersonalFilesTreeVo personalFilesTreeVo = personalFilesTreeService.selectTree(query);
        return R.ok(personalFilesTreeVo);
    }

    /**
     *查询个人树分页
     * @param query
     * @param pageable
     * @return
     */
    @GetMapping(value = "/selectTreePage")
    public R<TableDataInfo<PersonalFilesTreeVo>> selectTreePage(PersonalFilesTreeParam query, Pageable pageable) {
        TableDataInfo<PersonalFilesTreeVo> info = fileService.selectTreePage(query, pageable);
        return R.ok(info);
    }


    /**
     * 创建个人文件夹
     * @param treeDto
     * @return
     */
//    @Log("创建个人文件夹")
//    @ApiOperation("创建文件夹")
    @PostMapping(value = "/createFolder")
    @ResponseBody
    public R<PersonalFilesTreeVo> createFolder(@Valid @RequestBody PersonalFilesTreeDto treeDto) throws BadRequestException {
        if (StringUtils.isEmpty(treeDto.getFolderName())) {
            throw new BadRequestException("缺少关键 参数,'文件夹名称'");
        }
        LoginUser user = LoginHelper.getLoginUser();
        PersonalFilesTree filesTrees = personalFilesTreeService.createFolder(treeDto.getParentId(), treeDto.getFolderName(), user);
        if (ObjectUtils.isNotEmpty(filesTrees)) {
//            PersonalFilesTreeVo vo = ConvertUtil.convert(filesTrees, PersonalFilesTreeVo.class);
            PersonalFilesTreeVo vo = MapstructUtils.convert(filesTrees, PersonalFilesTreeVo.class);
            return R.ok(vo);
//            return BaseRespResult.successResult(vo);
        } else {
//            return BaseRespResult.errorResult("创建文件夹，失败！！！");
            return R.fail("创建文件夹，失败！！！");
        }
    }


    /**
     * 个人文档:设置节点为置顶
     * @param top
     * @return
     */
//    @Log("个人文档:设置节点为置顶")
//    @ApiOperation("个人文档:设置节点为置顶")
    @PostMapping(value = "/top")
    public R<Boolean> setTreeTop(@RequestBody FilesTreeTop top) {
//        boolean b = fileService.setTreeTop(top);
        return R.ok(fileService.setTreeTop(top));
    }


    /**
     * 个人树复制
     * @param chooseAPath
     * @return
     */
//    @Log("个人树复制")
//    @ApiOperation("个人树复制")
    @PostMapping(value = "/treeCopy")
    @ResponseBody
//    @ApiImplicitParams({
////            @ApiImplicitParam(name = "parentId",value = "父类ID",dataType = "String")
//    })
    @Transactional
    public R treeCopy(@RequestBody RecoverFileChooseAPath chooseAPath) throws BadRequestException {
        if (chooseAPath != null
            && CollectionUtils.isEmpty(chooseAPath.getIds())
            && StringUtils.isEmpty(chooseAPath.getParentId())
            && chooseAPath.getIds().size() >= 1
        ) {
            throw new BadRequestException("缺少数据");
        }
        return fileService.fileTreeCopy(chooseAPath);
    }


    /**
     * 修改文件名称
     * @param treeDto
     * @return
     */
//    @Log("修改文件名称")
//    @ApiOperation("修改文件名称")
    @PostMapping(value = "/updateName")
    @ResponseBody
    @Transactional
    public R updateName(@Valid @RequestBody PersonalFilesTreeDto treeDto) throws BadRequestException {
        if (StringUtils.isEmpty(treeDto.getId())) {
            throw new BadRequestException("缺少关键 参数,'文件夹编号'");
        }
        if (StringUtils.isEmpty(treeDto.getFolderName())) {
            throw new BadRequestException("缺少关键 参数,'文件夹名称'");
        }
        boolean folder = fileService.updateName(treeDto.getId(), treeDto.getFolderName());

        //查询文件信息
        PersonalFilesTree personalFilesTree = personalFilesTreeService.selectById(treeDto.getId());
        //修改es中的文件数据
        if (personalFilesTree.getEsId() != null) {
            try {
                RemoteEsFilesTree remoteEsFilesTree = new RemoteEsFilesTree();
                remoteEsFilesTree.setId(personalFilesTree.getId());
                remoteEsFilesTree.setEsId(personalFilesTree.getEsId());
                remoteEsFilesTree.setSuperiorsIds(personalFilesTree.getSuperiorsIds());
                remoteEsFilesTree.setParentId(personalFilesTree.getParentId());
                remoteEsFilesTree.setRealName(personalFilesTree.getRealName());
                remoteEsFilesTree.setSuffix(personalFilesTree.getSuffix());
                remoteEsFilesTree.setType(personalFilesTree.getType());
                remoteEsFilesTree.setStorageId(personalFilesTree.getStorageId());
                remoteEsFilesTree.setSize(personalFilesTree.getSize());
                remoteEsFilesTree.setLibraryType(OssModuleType.Personal.getCode());
                remoteEsFilesTree.setVersionId(personalFilesTree.getEdition());
                remoteEsFilesTree.setVersionName(personalFilesTree.getEditionName());
                remoteEsFilesTree.setCreateBy(Long.valueOf(personalFilesTree.getCreateId()));
                remoteEsFilesTree.setCreateTime(personalFilesTree.getCreateTime());
                remoteEsFilesTree.setUpdateBy(Long.valueOf(personalFilesTree.getCreateId()));
                remoteEsFilesTree.setUpdateTime(personalFilesTree.getUpdateTime());
                remoteEsFilesTree.setUserIdList(Arrays.asList(personalFilesTree.getCreateId()));
                remoteOssEsService.update(remoteEsFilesTree);
            } catch (Exception e) {

            }

        }


        if (ObjectUtils.isNotEmpty(folder)) {
//            PersonalFilesTreeVo vo = ConvertUtil.convert(filesTrees, PersonalFilesTreeVo.class);
            return R.ok();
        } else {
            return R.fail("修改文件名称，失败！！！");
        }
    }


    /**
     * 个人树移动
     * @param chooseAPath
     * @return
     */
//    @Log("个人树移动")
//    @ApiOperation("个人树移动")
    @PostMapping(value = "/fileTreeMove")
    @ResponseBody
    @Transactional
    public R fileTreeMove(@RequestBody RecoverFileChooseAPath chooseAPath) throws BadRequestException {
        if (
            chooseAPath != null
                && CollectionUtils.isEmpty(chooseAPath.getIds())
                && StringUtils.isEmpty(chooseAPath.getParentId())
                && chooseAPath.getIds().size() >= 1
        ) {
            throw new BadRequestException("缺少数据");
        }
        return fileService.fileTreeMove(chooseAPath);
    }


    /**
     * 修改文件描述
     * @param treeDto
     * @return
     */
//    @Log("修改文件描述")
//    @ApiOperation("修改文件描述")
    @PostMapping(value = "/updateRemarks")
    @ResponseBody
    @Transactional
    public R updateRemarks(@Valid @RequestBody PersonalFilesTreeRemarksDto treeDto) throws BadRequestException {
        if (StringUtils.isEmpty(treeDto.getId())) {
            throw new BadRequestException("缺少关键 参数,'文件编号'");
        }
        boolean folder = fileService.updateRemarks(treeDto.getId(), treeDto.getRemarks());
        if (ObjectUtils.isNotEmpty(folder)) {
            return R.ok();
//            return BaseRespResult.success();
        } else {
            return R.fail("修改文件备注,失败！！！");
//            return BaseRespResult.errorResult("修改文件备注,失败！！！");
        }
    }


    /**
     * 查询个人树
     * @param query
     * @return
     */
//    @Log("查询个人树")
//    @ApiOperation("查询个人树")
    @GetMapping(value = "/selectPersonalTree")
    @ResponseBody

    public R<PersonalFilesTreeVo> selectPersonalTree(PersonalFilesTreeParam query) {
        PersonalFilesTreeVo list = fileService.selectPersonalTree(query);
        return R.ok(list);
    }


    /**
     * 提交到企业
     */
    @PostMapping("/personal/to/enterprise")
    public R personalToEnterprise(Long fileId, String parentId, String fileName) {

        fileService.personalToEnterprise(fileId, parentId, fileName);
        return R.ok();
    }


    /**
     * 个人提交企业库
     * @param id
     * @param enterpriseId
     * @return
     */
//    @Log("个人提交企业库")
//    @ApiOperation("个人提交企业库")
    @GetMapping(value = "/commitEnterprise")
    public R commitEnterprise(String id,String enterpriseId) throws BadRequestException {


        PersonalToEnterpriseDto toEnterpriseDto = personalFilesTreeService.assembleTeamToEnterprise(id);
        LoginUser user = LoginHelper.getLoginUser();

        //上传至企业库
        enterpriseFilesTreeService.createFolder(toEnterpriseDto, String.valueOf(user.getUserId()),null,user.getUsername(),enterpriseId,1);
        return R.ok();
    }


    /**
     * 查询个人树(分页)
     * @param query
     * @param pageable
     * @return
     */
    @GetMapping(value = "/selectPersonalTreePage")
    @ResponseBody
    public R<PersonalFilesTreeVo> selectPersonalTreePage(PersonalFilesTreeParam query, Pageable pageable) {
        PersonalFilesTreeVo list = fileService.selectPersonalTreePage(query, pageable);
        return R.ok(list);
//        return BaseRespResult.successResult(list);
    }

    /**
     * 查询个人AI功能是否开启
     * @param configKey
     * @return
     */
    @GetMapping(value = "/selectConfigByKey")
    @ResponseBody
    public String getPersonalChatStatus(@RequestParam("configKey") String configKey) {
        //查询参数配置中是否开启
        return remoteConfigService.selectConfigByKey("personal.chat");
//        return remoteLargeModelService.selectConfigByKey(configKey);
    }

    /**
     * 个人文档上传到专家知识库
     * @param toExpertAppDto
     * @return
     */
    @PostMapping("/file/to/expert/app")
    public R fileToExpertApp(@RequestBody ToExpertAppDto toExpertAppDto) throws BadRequestException {
        personalFilesTreeService.fileToExpertApp(toExpertAppDto);
        return R.ok();
    }

    /**
     * 个人文档重新上传到专家知识库
     * @param toExpertAppDto
     * @return
     */
    @PostMapping("/again/file/to/expert/app")
    public R againFileToExpertApp(@RequestBody ToExpertAppDto toExpertAppDto) {
        personalFilesTreeService.againFileToExpertApp(toExpertAppDto);
        return R.ok();
    }












}
